package br.com.duosoftware.sisvendaweb.hibernate;

import java.sql.Connection;
import java.sql.SQLException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SessionFactoryImplementor;


/**
 *
 * @author daniel
 *
 */ 
public class HibernateUtil {

    private static HibernateUtil me;
    private static SessionFactory sessionFactory;

    static {

        Configuration cfg = new Configuration().configure("br/com/jbssistemas/sisvendaweb/hibernate/hibernate.cfg.xml");         
        StandardServiceRegistryBuilder sb = new StandardServiceRegistryBuilder();
        sb.applySettings(cfg.getProperties());
        StandardServiceRegistry standardServiceRegistry = sb.build();                   
        sessionFactory = cfg.buildSessionFactory(standardServiceRegistry);
        
    }
    
    public static Session getSession(){
    
        return sessionFactory.openSession();
        
    }
    
    public static Connection getConnection() throws SQLException{
    
        SessionFactoryImplementor sfi = (SessionFactoryImplementor) HibernateUtil.getSession().getSessionFactory();
        
        ConnectionProvider connectionProvider = sfi.getConnectionProvider();
        
        Connection connection = connectionProvider.getConnection();
        
        return connection;
        
    }
    
    public static HibernateUtil getInstance(){
        if(me == null){
            me = new HibernateUtil();
        }
        return me;
    }

}
